/**
 * DB库
 */
const MongoDB = require('mongodb')
const MongoClient = MongoDB.MongoClient
const ObjectID = MongoDB.ObjectID

const Config = require('./config')

class Db {

  /* 单例：解决多次实例化实例不共享的问题 */
  static getInstance() {
    if (!Db.instance) {
      Db.instance = new Db()
    }
    return Db.instance
  }

  constructor() {
    //属性，放db对象
    this.dbClient = ''
    //实例化的时候连接数据库
    this.connect()
  }

  /* 连接数据库 */
  connect() {
    let _that = this
    return new Promise((resolve, reject) => {
      
      if (!_that.dbClient) { //解决数据库多次了解的问题
        MongoClient.connect(Config.dbUrl, { useUnifiedTopology: true }, (error, client) => {
          if (error) {
            reject(error)
          } else {
            _that.dbClient = client.db(Config.dbName)
            resolve(_that.dbClient)
          }
        })
      } else {
        resolve(_that.dbClient)
      }
      
    })
  }

  /* 查询数据 */
  find(collectionName, json) {
    return new Promise((resolve, reject) => {
      this.connect().then((db) => {
        const result = db.collection(collectionName).find(json)
        result.toArray((err, docs) => {
          if (err) {
            reject(err)
            return
          }
          resolve(docs)
        })
      })
    })
  }

  /* 更新数据 */
  update(collectionName, json1, json2) {
    return new Promise((resolve, reject) => {
      this.connect().then((db) => {
        db.collection(collectionName).updateOne(json1, {
          $set: json2
        }, (err, result) => {
          if (err) {
            reject(err)
          } else {
            resolve(result)
          }

        })
      })
    })
  }

  /* 插入数据 */
  insert(collectionName, json) {
    return new Promise((resolve, reject) => {
      this.connect().then((db) => {
        db.collection(collectionName).insertOne(json, (err, result) => {
          if (err) {
            reject(err)
          } else {
            resolve(result)
          }

        })
      })
    })
  }

  /* 删数据 */
  remove(collectionName, json) {
    return new Promise((resolve, reject) => {
      this.connect().then((db) => {
        db.collection(collectionName).removeOne(json, (err, result) => {
          if (err) {
            reject(err)
          } else {
            resolve(result)
          }

        })
      })
    })
  }

  /* 获取ObjectID */
  getObjectId(id) {
    return new ObjectID(id)
  }
}

module.exports = Db.getInstance()